<?php
namespace Common\Service;

class FileService {
    protected $error = '';
    protected $mime_map = array(
        'application/envoy' => 'evy',
        'application/fractals' => 'fif',
        'application/futuresplash' => 'spl',
        'application/hta' => 'hta',
        'application/internet-property-stream' => 'acx',
        'application/mac-binhex40' => 'hqx',
        'application/msword' => 'dot',
        'application/octet-stream' => 'lzh',
        'application/oda' => 'oda',
        'application/olescript' => 'axs',
        'application/pdf' => 'pdf',
        'application/pics-rules' => 'prf',
        'application/pkcs10' => 'p10',
        'application/pkix-crl' => 'crl',
        'application/postscript' => 'ps',
        'application/rtf' => 'rtf',
        'application/set-payment-initiation' => 'setpay',
        'application/set-registration-initiation' => 'setreg',
        'application/vnd.ms-excel' => 'xlw',
        'application/vnd.ms-outlook' => 'msg',
        'application/vnd.ms-pkicertstore' => 'sst',
        'application/vnd.ms-pkiseccat' => 'cat',
        'application/vnd.ms-pkistl' => 'stl',
        'application/vnd.ms-powerpoint' => 'ppt',
        'application/vnd.ms-project' => 'mpp',
        'application/vnd.ms-works' => 'wps',
        'application/winhlp' => 'hlp',
        'application/x-bcpio' => 'bcpio',
        'application/x-cdf' => 'cdf',
        'application/x-compress' => 'z',
        'application/x-compressed' => 'tgz',
        'application/x-cpio' => 'cpio',
        'application/x-csh' => 'csh',
        'application/x-director' => 'dxr',
        'application/x-dvi' => 'dvi',
        'application/x-gtar' => 'gtar',
        'application/x-gzip' => 'gz',
        'application/x-hdf' => 'hdf',
        'application/x-internet-signup' => 'isp',
        'application/x-iphone' => 'iii',
        'application/x-javascript' => 'js',
        'application/x-latex' => 'latex',
        'application/x-msaccess' => 'mdb',
        'application/x-mscardfile' => 'crd',
        'application/x-msclip' => 'clp',
        'application/x-msdownload' => 'dll',
        'application/x-msmediaview' => 'mvb',
        'application/x-msmetafile' => 'wmf',
        'application/x-msmoney' => 'mny',
        'application/x-mspublisher' => 'pub',
        'application/x-msschedule' => 'scd',
        'application/x-msterminal' => 'trm',
        'application/x-mswrite' => 'wri',
        'application/x-netcdf' => 'nc',
        'application/x-perfmon' => 'pmw',
        'application/x-pkcs12' => 'pfx',
        'application/x-pkcs7-certificates' => 'spc',
        'application/x-pkcs7-certreqresp' => 'p7r',
        'application/x-pkcs7-mime' => 'p7m',
        'application/x-pkcs7-signature' => 'p7s',
        'application/x-sh' => 'sh',
        'application/x-shar' => 'shar',
        'application/x-shockwave-flash' => 'swf',
        'application/x-stuffit' => 'sit',
        'application/x-sv4cpio' => 'sv4cpio',
        'application/x-sv4crc' => 'sv4crc',
        'application/x-tar' => 'tar',
        'application/x-tcl' => 'tcl',
        'application/x-tex' => 'tex',
        'application/x-texinfo' => 'texinfo',
        'application/x-troff' => 'tr',
        'application/x-troff-man' => 'man',
        'application/x-troff-me' => 'me',
        'application/x-troff-ms' => 'ms',
        'application/x-ustar' => 'ustar',
        'application/x-wais-source' => 'src',
        'application/x-x509-ca-cert' => 'der',
        'application/ynd.ms-pkipko' => 'pko',
        'application/zip' => 'zip',
        'audio/basic' => 'snd',
        'audio/mid' => 'rmi',
        'audio/mpeg' => 'mp3',
        'audio/x-aiff' => 'aiff',
        'audio/x-mpegurl' => 'm3u',
        'audio/x-pn-realaudio' => 'ram',
        'audio/x-wav' => 'wav',
        'image/bmp' => 'bmp',
        'image/cis-cod' => 'cod',
        'image/gif' => 'gif',
        'image/ief' => 'ief',
        'image/jpeg' => 'jpg',
        'image/pipeg' => 'jfif',
        'image/svg+xml' => 'svg',
        'image/tiff' => 'tiff',
        'image/x-cmu-raster' => 'ras',
        'image/x-cmx' => 'cmx',
        'image/x-icon' => 'ico',
        'image/x-portable-anymap' => 'pnm',
        'image/x-portable-bitmap' => 'pbm',
        'image/x-portable-graymap' => 'pgm',
        'image/x-portable-pixmap' => 'ppm',
        'image/x-rgb' => 'rgb',
        'image/x-xbitmap' => 'xbm',
        'image/x-xpixmap' => 'xpm',
        'image/x-xwindowdump' => 'xwd',
        'message/rfc822' => 'nws',
        'text/css' => 'css',
        'text/h323' => '323',
        'text/html' => 'stm',
        'text/iuls' => 'uls',
        'text/plain' => 'txt',
        'text/richtext' => 'rtx',
        'text/scriptlet' => 'sct',
        'text/tab-separated-values' => 'tsv',
        'text/webviewhtml' => 'htt',
        'text/x-component' => 'htc',
        'text/x-setext' => 'etx',
        'text/x-vcard' => 'vcf',
        'video/mpeg' => 'mpv2',
        'video/quicktime' => 'qt',
        'video/x-la-asf' => 'lsx',
        'video/x-ms-asf' => 'asx',
        'video/x-msvideo' => 'avi',
        'video/x-sgi-movie' => 'movie',
        'x-world/x-vrml' => 'xof',
    );

    /**
     * 保存base64数据图片
     * @param $data
     * @param bool $filename
     * @return bool|string
     */
    public function save_base64img($data, $filename=false)
    {
        $save_dir = rtrim(C('CUSTOM_UPLOAD_CONFIG.rootPath'), '/\\') . '/base64/';
        if (!is_dir($save_dir)) mkdir($save_dir, 0777, true);
        $per = '!^data:\s*(image\/\w+);base64,\s*(.+?)$!Uis';
        if (preg_match($per, $data, $m)) {
            if(!$filename) {
                // 默认文件名
                $mime = strtolower($m[1]);
                $ext = $this->mime_map[$mime] ?: 'jpg';
                $filename = time().'_'.uniqid() . '.' . $ext;
                $save_path = $save_dir . $filename;
            }
            $base64 = $m[2];
            // 逆向数据
            $debase64 = base64_decode($base64);
            if (!$debase64) {
                $this->error = '解码失败了';
                return false;
            }
            if (file_put_contents($save_path, $debase64)) {
                return $save_path;
            } else {
                $this->error = '保存文件时出现了点问题';
                return false;
            }
        } else {
            $this->error = '没有发现图片数据';
            return false;
        }
    }

    /**
     * 批量保存base64图片
     * @param $list
     * @param bool $namecall
     * @return array
     */
    public function mutiple_save_base64img($list, $namecall = false) {
        $pathes = [];
        foreach ($list as $k=>$item) {
            $pathes[$k] = $item;
            if(is_callable($namecall)) {
                $name = $namecall($item);
            }
            $res= $this->save_base64img($item, $name);
            if ($res) $pathes[$k] = $res;
        }
        return $pathes;
    }

    public function uploadOne($field, $config)
    {
        // 默认配置
        $def_config = [
            // 设置附件上传大小
            'maxSize' => 0,
            // 设置附件上传类型
            'exts' => array('bmp', 'jpg', 'png', 'tiff', 'gif', 'pcx', 'tga', 'exif', 'fpx', 'svg', 'psd', 'cdr', 'pcd', 'dxf', 'ufo', 'eps', 'ai', 'raw', 'WMF', 'webp'),
            // 设置附件上传根目录
            'rootPath' => C('CMS_UPLOADDIR'),
        ];
        $config = array_merge($def_config, $config);
        // 实例化上传类
        $upload = new \Think\Upload($config);
        // 上传单个文件
        if (is_array($field)) {
            $file = $field;
        } else {
            $file = $_FILES[$field];
        }
        $info = $upload->uploadOne($file);
        if (!$info) {
            // 上传错误提示错误信息
            $this->error = $upload->getError();
            return false;
        }
        // 上传成功 获取上传文件信息
        $url = C('CMS_UPLOADDIR') . $info['savepath'] . $info['savename'];
        return $url;
    }

    public function getError(){
        return $this->error;
    }
}